package com.chat.common.chat.service.impl;

import com.chat.common.chat.dao.ContactDao;
import com.chat.common.chat.domain.dto.MsgReadInfoDTO;
import com.chat.common.chat.domain.entity.Message;
import com.chat.common.chat.service.IContactService;
import com.chat.common.common.utils.AssertUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ContactServiceImpl implements IContactService {
    @Resource
    private ContactDao contactDao;

    /**
     * 查询自己某些消息已读未读数
     *
     * @return
     */
    @Override
    public Collection<MsgReadInfoDTO> getMsgReadInfo(List<Message> messageList) {
        Map<Long, List<Message>> roomGroup = messageList.stream().collect(Collectors.groupingBy(Message::getRoomId));
        AssertUtil.equal(roomGroup.size(),1,"只能查相同房间下的消息");
        Long roomId = roomGroup.keySet().iterator().next();
        //消息总数
        Integer totalCount = contactDao.getTotalCount(roomId);
       return messageList.stream()
                .map(message->{
                    MsgReadInfoDTO readInfo = new MsgReadInfoDTO();
                    readInfo.setMsgId(message.getId());
                    Integer readCount = contactDao.getReadCount(message);
                    readInfo.setReadCount(readCount);
                    readInfo.setUnReadCount(totalCount-readCount-1);
                    return readInfo;
                }).collect(Collectors.toList());
    }
}
